package com.ehotting.edsta.reliability.service.impl;

import cn.hutool.core.io.FileUtil;
import com.ehotting.eaf.core.domain.R;
import com.ehotting.eaf.core.exception.ServiceException;
import com.ehotting.eaf.core.utils.StringUtils;
import com.ehotting.eaf.security.service.TokenService;
import com.ehotting.edsta.mqbd.reliability.api.bean.MQReliabilityData;
import com.ehotting.edsta.mqbd.reliability.api.domain.AnsysRunnerModel;
import com.ehotting.edsta.mqbd.reliability.api.domain.SimulateDto;
import com.ehotting.edsta.mqbd.reliability.api.domain.SimulateResultDto;
import com.ehotting.edsta.reliability.RemotePathConstant;
import com.ehotting.edsta.reliability.config.BaseProperties;
import com.ehotting.edsta.reliability.enums.SimutypeEnum;
import com.ehotting.edsta.reliability.hprose.IAnsysRunner;
import com.ehotting.edsta.reliability.service.ICommonService;
import com.ehotting.edsta.system.api.RemoteFileService;
import com.ehotting.mqbd.api.bean.MqApplicationContext;
import com.ehotting.mqbd.api.enums.SendTypeEnum;
import com.ehotting.mqbd.api.enums.TopicEnum;
import com.ehotting.mqbd.core.service.MQService;
import com.ehotting.mqbd.core.manager.AgentLinkManager;
import hprose.client.HproseClient;
import hprose.client.HproseHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommonServiceImpl implements ICommonService {

    @Autowired
    private BaseProperties properties;

    @Autowired
    private RemoteFileService remoteFileService;

    @Autowired
    private MqApplicationContext mqApplicationContext;

    @Autowired
    private MQService mqService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private AgentLinkManager agentLinkManager;



    @Override
    public SimulateResultDto runAnsys(SimulateDto simulateDto) {
        Integer simutype = simulateDto.getSimutype();
        String filepath = simulateDto.getFilepath();
        String bucketName = simulateDto.getBucketName();
        List<String> fileList = simulateDto.getFileList();
        SimutypeEnum simutypeEnum = SimutypeEnum.getByKey(simutype);

        AnsysRunnerModel model = new AnsysRunnerModel();
        model.SourceWorkDir = filepath;
        model.JobName = simutypeEnum.getName()/*+"-"+ DateUtils.dateTimeNow()*/;
//        model.EntryPointName = simutypeEnum.getValue()+"Input.dat";

        Map<String,String> datas = new HashMap<>();
        // 读取minio文件服务器文件
        boolean isGotFile = true;
        for (String path : fileList) {
            if (path.contains("Input.dat")){
                model.EntryPointName = FileUtil.mainName(path)+"."+FileUtil.extName(path);
            }
            R<byte[]> result = remoteFileService.getBytesFromMinio(path, bucketName);
            byte[] data1 = result.getData();
            if (data1==null){
                isGotFile = false;
                break;
            }
            String data = new String(data1,StandardCharsets.UTF_8);
            datas.put(FileUtil.mainName(path)+"."+FileUtil.extName(path),data);
        }

//        model.EntryPointName = fileList.stream().filter(item -> fileList.contains("Input.dat")).collect(Collectors.toList()).get(0);

        if (!isGotFile){
            // 获取文件失败
            log.error("get files from minio failed");
            throw new ServiceException("获取文件失败");
        }

        model.Datas = datas;

        String urlPrefix = properties.getUrl();
        Integer timeout = properties.getTimeout();
        Integer waitFor = properties.getWaitFor();

        model.TimeOut = timeout;
        model.WaitFor = waitFor;
        model.ResultName = StringUtils.replace(model.EntryPointName,"Input","Result");

        Long userId = tokenService.getLoginUser().getUserid();
        String agentId = agentLinkManager.genAgentId(mqApplicationContext.getModule(),userId,"0");

        String uri = urlPrefix + "/" + RemotePathConstant.ansysRemoteRunner+ "/";

        MQReliabilityData data = MQReliabilityData.create(TopicEnum.BLOCK, mqApplicationContext, agentId, "");
        data.setSync(false);
        data.setRequestUrl(uri);
        data.setRequest(model);

        data.setLogRequest(false);
        data.setSendType(new SendTypeEnum[]{SendTypeEnum.REDIS_REQUEST_BODY});

        MQReliabilityData response = (MQReliabilityData) mqService.request(data, (timeout.longValue()));

        if (response == null){
            log.error("get result from rocket mq timeout");
            throw new ServiceException("获取结果超时");
        }
        if (response.getResponse()==null){
            log.error("get result from ansys timeout");
            throw new ServiceException("获取结果超时");
        }
        return response.getResponse();

    }

    @Override
    public String helloWorld() {
        String urlPrefix = properties.getUrl();
        String uri = urlPrefix + "/" + RemotePathConstant.ansysRemoteRunner+ "/";
        HproseClient client = new HproseHttpClient();
        client.setTimeout(5*60);

        client.useService(uri);
        log.info("uri:{}",uri);

        IAnsysRunner ansysRunner = client.useService(IAnsysRunner.class);

        String msg2 = "hello>>>>>";
        log.info("调用接口传递的参数：{}", msg2);

        String result = ansysRunner.HelloWorld(msg2);

        log.info("result:{}",result);
        return result;
    }
}
